package com.hu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hu.reggie.common.R;
import com.hu.reggie.pojo.Category;
import com.hu.reggie.service.impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CateGoryController {
    @Autowired
    private CategoryServiceImpl categoryService;
    // 新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        log.info("新增分类成功");

        return R.success("新增分类成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        log.info("page:{},pageSize{}",page,pageSize);

        // 创建分页构造器
        Page<Category> pageInfo=new Page<>(page,pageSize);
        // 创建条件构造器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    // 根据id删除分类
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除分类,id为{}",id);
        categoryService.remove(id);

        return R.success("删除成功");
    }

    // 根据id修改分类
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息：{}",category);
        categoryService.updateById(category);

        return R.success("修改成功");
    }

    // 根据类型type查询分类
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        // 创建条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        // 添加条件
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        List<Category> categoryList = categoryService.list(lambdaQueryWrapper);

        return R.success(categoryList);
    }
}
